/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lab07;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

/**
 *
 * @author Johnny
 */
public class RaceCanvas extends JPanel {

  private static final int JUMPSIZE = 20;
  private int positions[];
  private int finished[];
  private int finishedNr = 0;
  private Control c;
  private int n;
  private Image car;
  private GUI parent;

  /**
   * Constructor
   * @param n The number of racers.
   * @param parent The parent GUI that will be signalled when the race is over
   */
  public RaceCanvas(int n, GUI parent) {
    positions = new int[n];
    finished = new int[n];
    this.parent = parent;

    try {
      ClassLoader cl = this.getClass().getClassLoader();
      //car = ImageIO.read(new File("Res\\top.jpg"));
      car = ImageIO.read(cl.getResource("Res/top.jpg"));
    } catch (IOException e) {
      System.out.println(e.toString());
      System.exit(1);
    }

    this.n = n;

    this.setPreferredSize(new Dimension(1100, n * 100));
    this.repaint();
    c = new Control(n, this);

  }

  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    this.setBackground(Color.white);
    g.setColor(Color.red);
    for (int i = 0; i < n; i++) {
      g.drawImage(car, 1 + (positions[i]) * JUMPSIZE, 1 + (i * 100), this);
      if (finished[i] > 0) {
        g.drawString(Integer.toString(finished[i]), 1070, 20 + (i * 100));
      }
      //g.fillRect(1+(positions[i])*JUMPSIZE, 1+(i*100), 50, 50);
    }

  }

  /**
   *
   * @param index
   * @param pos
   */
  public void setPos(int index, int pos) {
    positions[index] = pos;
    if (pos == (Auto.N - 1)) {
      ++this.finishedNr;
      finished[index] = this.finishedNr;
      if (this.finishedNr == this.n) {
        parent.finished();
      }
    }
    this.repaint();
  }

  /**
   *
   */
  public void stopAll() {
    c.stopAll();
  }
}
